package com.example.communitysystem.controller;

import com.example.communitysystem.dto.CommentDTO;
import com.example.communitysystem.dto.QuestionDTO;
import com.example.communitysystem.enums.CommentTypeEnum;
import com.example.communitysystem.mapper.QuestionMapper;
import com.example.communitysystem.model.User;
import com.example.communitysystem.service.CommentService;
import com.example.communitysystem.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class QuestionDetailController {

    private QuestionMapper questionMapper;

    private QuestionService questionService;

    private CommentService commentService;

    @GetMapping("/questiondetail/{id}")
    public String questionDetail(
            @PathVariable(name = "id") Long id,
            Model model,
            HttpServletRequest request
    ){
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            model.addAttribute("message","当前操作需要登录，请登录后重试！");
            return "error";
        }
        //获取当前用户指定的问题信息
        QuestionDTO questionDTO = questionService.getQuestionById(id);
        //累加阅读数
        questionService.addReadCount(id);

        //获取当前问题id的全部一级评论
        List<CommentDTO> commentDTOList = commentService.getCommentDTOListByTargetId(questionDTO.getId(), CommentTypeEnum.QUESTION.getType());

        //获得相关问题信息
        List<QuestionDTO> relatedQuestions = questionService.getRelatedQuestionDTOList(questionDTO);

        model.addAttribute("relatedQuestions",relatedQuestions);
        if(commentDTOList != null){
            model.addAttribute("commentDTOList",commentDTOList);
        }
        model.addAttribute("questionDTO",questionDTO);


        return "questiondetail";
    }


    @Autowired
    public void setCommentService(CommentService commentService) {
        this.commentService = commentService;
    }

    @Autowired
    public void setQuestionMapper(QuestionMapper questionMapper) {
        this.questionMapper = questionMapper;
    }

    @Autowired
    public void setQuestionService(QuestionService questionService) {
        this.questionService = questionService;
    }
}
